from expression import expression
from expression import environment 
from jsobject import closure

class functionBinding(expression):
	def __init__(self, functions, body):
		if(len(functions) == 0):
			print "ERROR:Figure out how in gods name we have a functionBinding with 0 functions!!!!"
		self.functions = functions # function defs
		self.body = body
		
	def evaluate(self, env):
	#	print "FunBind: ",
		functions = self.functions
		funcClosures = []
		
		#First, make all the closures
		for f in functions:
			newclosure = closure(f.getParams(),f.getBody(),env)
			funcClosures.append(newclosure)
			
		#ex: functions: [a(),b()], closures: [a(), b()]
		newEnv = env
		i = 0
		
		for f in functions:
			# add each closure the environment
		#	print f.getName(), ", ",
			newEnv = environment(f.getName(),funcClosures[0],newEnv)
			i += 1
		
		# newEnv <- a(), b()
		# add all closures to all other closures
		# I really hope this works
		for c in funcClosures:
			for j in range(0, len(functions)):
				thisEnv = c.getEnv()
				thisEnv = environment(functions[j].getName(), funcClosures[j], thisEnv)
				c.setEnv(thisEnv)
				
		self.body.evaluate(newEnv)
